package cn.xy.third.sms.impl;

import cn.hutool.json.JSONUtil;
import cn.xy.third.sms.SmsService;
import cn.xy.third.sms.aliyun.AliyunConfig;
import cn.xy.third.sms.aliyun.SmsSendResult;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author lixue
 */
@Slf4j
@Service("aliyunSmsService")
public class AliyunSmsServiceImpl implements SmsService {

    @Autowired
    private AliyunConfig aliyunConfig;

    @Override
    public boolean sendSms(String mobile, String signName, String templateId, Map<String, String> templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunConfig.getAccessKeyID(), aliyunConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");

        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateId);
        request.putQueryParameter("TemplateParam", JSONUtil.toJsonStr(templateParam));
        try {
            CommonResponse response = client.getCommonResponse(request);
            SmsSendResult smsSendResult = JSONUtil.toBean(response.getData(), SmsSendResult.class);
            log.debug("sendSms response => {}", smsSendResult);
            return "OK".equals(smsSendResult.getCode());
        } catch (ClientException e) {
            log.error("sendSms error =>", e);
            return false;
        }
    }

}
